#!/usr/bin python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/18 15:26
# @Author  : hhr
import pymysql, datetime, subprocess, calendar
from chinese_calendar import is_workday


class AutomaticScheduling():
    def __init__(self, development):
        self.conn = pymysql.connect(host="localhost", port=3306, user='root', password='123456' if development == 'test' else 'jsyy2021', db="administration", use_unicode=True, charset='utf8')
        self.cur = self.conn.cursor()
        self.duty_leader_list = []

    def DateJudgment(self, current_date):
        """判断所传日期是否是工作日"""
        if is_workday(current_date):
            return 1
        else:
            return 2

    def UpgradeInstallationPackage(self):
        """升级判断日期是否是工作日的库"""
        subprocess.call("pip3 uninstall chinesecalendar", shell=True)
        subprocess.call("pip3 install chinesecalendar -i https://pypi.tuna.tsinghua.edu.cn/simple", shell=True)

    def FirstLineWork(self):
        """一线班排班"""
        today = datetime.date.today()
        year = today.year if today.month != 12 else today.year + 1
        month = today.month + 1 if today.month != 12 else 1

        select_sql = "SELECT id FROM `administration`.`personal_center_scheduling` WHERE `is_work` = '1' AND `type` = '1'"
        self.cur.execute(select_sql)
        id_number = self.cur.fetchall()[0][0]  # 当前月一线班最后一位值班人员

        _, num_days = calendar.monthrange(today.year, month)

        for i in range(1, num_days+1):
            # 更新排班表二线班值班状态
            updata_sql = f"UPDATE `personal_center_scheduling` SET is_work='0' WHERE id='{id_number}'"
            self.cur.execute(updata_sql)
            self.conn.commit()

            id_number += 1
            try:
                select_duty_leader = f"SELECT user_id FROM `administration`.`personal_center_scheduling` WHERE id='{id_number}' AND `type` = '1'"
                self.cur.execute(select_duty_leader)
                duty_leader = self.cur.fetchall()[0][0]  # 值班人员


                updata_duty_leader_sql = f"UPDATE `personal_center_scheduling` SET is_work='1' WHERE id='{id_number}'"
                self.cur.execute(updata_duty_leader_sql)
                self.conn.commit()
            except Exception as EF:
                # 查询二线班的第一位领导
                select_first_leader_sql = "SELECT id FROM `administration`.`personal_center_scheduling` WHERE `type` = '1'"
                self.cur.execute(select_first_leader_sql)
                id_number = self.cur.fetchall()[0][0]

                select_duty_leader = f"SELECT user_id FROM `administration`.`personal_center_scheduling` WHERE id='{id_number}'"
                self.cur.execute(select_duty_leader)
                duty_leader = self.cur.fetchall()[0][0]  # 值班领导

                updata_duty_leader_sql = f"UPDATE `personal_center_scheduling` SET is_work='1' WHERE id='{id_number}'"
                self.cur.execute(updata_duty_leader_sql)
                self.conn.commit()

            first_day_of_next_month = datetime.date(year, month, i)  # 例如：2024-06-01
            JudgmentFlag = self.DateJudgment(first_day_of_next_month)  # 是否是工作日

            insert_sql = f"INSERT INTO `personal_center_sortline` (type, date, user_id, day_type, is_deleted) VALUES('1', '{first_day_of_next_month}', {duty_leader}, 'a', '1')"
            self.cur.execute(insert_sql)
            self.conn.commit()

            if JudgmentFlag == 2:
                id_number += 1
                try:
                    select_duty_leader = f"SELECT user_id FROM `administration`.`personal_center_scheduling` WHERE id='{id_number}' AND `type` = '1'"
                    self.cur.execute(select_duty_leader)
                    duty_leader = self.cur.fetchall()[0][0]  # 值班人员

                    updata_duty_leader_sql = f"UPDATE `personal_center_scheduling` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()
                except Exception as EF:
                    # 查询二线班的第一位领导
                    select_first_leader_sql = "SELECT id FROM `administration`.`personal_center_scheduling` WHERE `type` = '1'"
                    self.cur.execute(select_first_leader_sql)
                    id_number = self.cur.fetchall()[0][0]

                    select_duty_leader = f"SELECT user_id FROM `administration`.`personal_center_scheduling` WHERE id='{id_number}'"
                    self.cur.execute(select_duty_leader)
                    duty_leader = self.cur.fetchall()[0][0]  # 值班领导

                    updata_duty_leader_sql = f"UPDATE `personal_center_scheduling` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()

                insert_sql1 = f"INSERT INTO `personal_center_sortline` (type, date, user_id, day_type, is_deleted) VALUES('1', '{first_day_of_next_month}', {duty_leader}, 'b', '1')"
                self.cur.execute(insert_sql1)
                self.conn.commit()

    def SecondLineWork(self):
        """二线班排班"""
        select_sql = "SELECT id FROM `administration`.`personal_center_scheduling` WHERE `is_work` = '1' AND `type` = '2'"
        self.cur.execute(select_sql)
        id_number = self.cur.fetchall()[0][0]  # 当前月二线班最后一位值班领导

        today = datetime.date.today()
        year = today.year if today.month != 12 else today.year + 1
        month = today.month + 1 if today.month != 12 else 1

        _, num_days = calendar.monthrange(today.year, month)

        for i in range(1, num_days+1):
            first_day_of_next_month = datetime.date(year, month, i)
            try:
                # 更新排班表二线班值班状态
                updata_sql = f"UPDATE `personal_center_scheduling` SET is_work='0' WHERE id='{id_number}'"
                self.cur.execute(updata_sql)
                self.conn.commit()

                id_number += 1
                try:
                    select_duty_leader = f"SELECT user_id FROM `administration`.`personal_center_scheduling` WHERE id='{id_number}'"
                    self.cur.execute(select_duty_leader)
                    duty_leader = self.cur.fetchall()[0][0]                  # 值班领导
                    self.duty_leader_list.append(duty_leader)

                    updata_duty_leader_sql = f"UPDATE `personal_center_scheduling` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()
                except Exception as EF:
                    # 查询二线班的第一位领导
                    select_first_leader_sql = "SELECT id FROM `administration`.`personal_center_scheduling` WHERE `type` = '2'"
                    self.cur.execute(select_first_leader_sql)
                    id_number = self.cur.fetchall()[0][0]  # 当前月二线班最后一位值班领导

                    select_duty_leader = f"SELECT user_id FROM `administration`.`personal_center_scheduling` WHERE id='{id_number}'"
                    self.cur.execute(select_duty_leader)
                    duty_leader = self.cur.fetchall()[0][0]  # 值班领导
                    self.duty_leader_list.append(duty_leader)

                    updata_duty_leader_sql = f"UPDATE `personal_center_scheduling` SET is_work='1' WHERE id='{id_number}'"
                    self.cur.execute(updata_duty_leader_sql)
                    self.conn.commit()

                insert_sql = f"INSERT INTO `personal_center_sortline` (type, date, user_id, day_type, is_deleted) VALUES('2', '{first_day_of_next_month}', {duty_leader}, 'a', '1')"
                self.cur.execute(insert_sql)
                self.conn.commit()
            except Exception as ER:
                print(ER)

    def main_fun(self):
        # 每年12月更新 chinesecalendar 库
        if datetime.datetime.now().month == 12:
            self.UpgradeInstallationPackage()

        self.FirstLineWork()
        self.SecondLineWork()
        self.cur.close()
        self.conn.close()


if __name__ == '__main__':
    development = 'test'
    AutomaticScheduling(development).main_fun()